package agents

import (
	"context"
	"errors"
	"k8sops/pkg/client"
	"k8sops/pkg/services"
	"log"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func NamespaceUpOff(namespace, sepcStatus string) (err error) {
	var replicas int32

	if sepcStatus == "on" {
		replicas = 1
	} else if sepcStatus == "off" {
		replicas = 0
	} else {
		return errors.New("unknown spec status")
	}

	k := client.K8sClientSet{}
	c, err := k.GetClientset()
	if err != nil {
		log.Fatal(err.Error())
		return
	}

	// 获取Deployments
	deployList, err := services.GetDeployments(namespace)
	for _, deploy := range deployList.Items {
		deploy.Spec.Replicas = int32Ptr(replicas)
		_, err := c.AppsV1().Deployments(namespace).Update(context.TODO(), &deploy, metav1.UpdateOptions{})
		if err != nil {
			panic(err.Error())
		}
	}

	// 获取StatefulSets
	statefulList, err := services.GetStatefulSets(namespace)
	for _, stateful := range statefulList.Items {
		stateful.Spec.Replicas = int32Ptr(replicas)
		_, err := c.AppsV1().StatefulSets(namespace).Update(context.TODO(), &stateful, metav1.UpdateOptions{})
		if err != nil {
			panic(err.Error())
		}
	}

	return
}

func int32Ptr(i int32) *int32 { return &i }
